package com.css.zfzx.sjcj.modules.drill.repository.impl;

import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.zfzx.sjcj.modules.drill.Entity.QhY06Entity;
import com.css.zfzx.sjcj.modules.drill.repository.QhY06NativeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;

/**
 * @Description
 * @Author Li Helei
 * @Date 2021/1/15 17:10
 * @Version V1.0
 */
@Repository
@PropertySource("classpath:platform-config.yml")
public class QhY06NativeRepositoryImpl implements QhY06NativeRepository {
    @PersistenceContext
    private EntityManager em;
    private static final Logger log = LoggerFactory.getLogger(QhY06NativeRepositoryImpl.class);

    @Override
    public Page<QhY06Entity> queryQhY06s(String drillId, int curPage, int pageSize,String sort,String order) {
        StringBuilder sql = new StringBuilder("select * from qh_y06 ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        //
        if (!PlatformObjectUtils.isEmpty(drillId)) {
            whereSql.append(" and drill_id = :drillId");
        }

        whereSql.append(" and is_valid = 1");
        if (!PlatformObjectUtils.isEmpty(sort)) {
            whereSql.append(" order by "+sort+" "+order);
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), QhY06Entity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from qh_y06 ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if (!PlatformObjectUtils.isEmpty(drillId)) {
            query.setParameter("drillId", drillId);
            countQuery.setParameter("drillId", drillId);
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<QhY06Entity> list = query.getResultList();
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Page<QhY06Entity> qhY06Page = new PageImpl<>(list, pageable, count.longValue());
        return qhY06Page;
    }

}
